// ==UserScript==
// @name              哆啦后台助手
// @namespace         http://luoyangxin.gitee.io/fordealhelper/fordealhelper.user.js
// @version           1.0.4
// @icon              http://luoyangxin.gitee.io/fordealhelper/logo.png
// @description       哆啦后台助手，（1.增序批量增加SKU编码）
// @author            Jack Luo
// @license           MIT
// @supportURL        https://gitee.com/luoyangxin/fordealHelper/blob/master/ 
// @updateURL         http://luoyangxin.gitee.io/fordealhelper/fordealhelper.user.js
// @downloadURL       http://luoyangxin.gitee.io/fordealhelper/fordealhelper.user.js
// @match             *://seller.fordeal.com/goods/publish/*
// @require           https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js
// @connect           *
// @run-at            document-idle
// @grant             unsafeWindow
// @grant             GM_xmlhttpRequest
// @grant             GM_setValue
// @grant             GM_getValue
// @grant             GM_info
// ==/UserScript==

/*
1.  20200726 Jack Luo - 添加增序批量填充SKU编码；
2.  20200727 Jack Luo - 添加填充SPU编码，修复填充的值提交无效的问题；
*/
;(() => {
    'use strict';
    const version = '1.0.0';
    const realVersion = GM_info.script.version; 
    const hostname = location.hostname; 
    let hasDone = false; 
    let Interval = '';
  
    function replaceLink(link) {
        return link ? link.replace(/&/g, '&amp;') : '';
    }
 
    function getCookie(e) {
        let o, t;
        let n = document, c = decodeURI;
        return n.cookie.length > 0 && (o = n.cookie.indexOf(e + "="), -1 != o) ? (o = o + e.length + 1, t = n.cookie.indexOf(";", o), -1 == t && (t = n.cookie.length), c(n.cookie.substring(o, t))) : "";
    }

    function setCookie(key, value, t) {
        let oDate = new Date();  //创建日期对象
        oDate.setTime(oDate.getTime() + t * 60 * 1000); //设置过期时间
        document.cookie = key + '=' + value + ';expires=' + oDate.toGMTString();  //设置cookie的名称，数值，过期时间
    }

    function getValue(name) {
        return GM_getValue(name);
    }

    function setValue(name, value) {
        GM_setValue(name, value);
    }

    function getStorage(key) {
        return localStorage.getItem(key);
    }

    function setStorage(key, value) {
        return localStorage.setItem(key, value);
    }
   
     

    //哆啦页面的助手
    function Forhelper() { 
        let GoodsPrice = undefined; 

        this.init = () => {             
            console.log('Forhelper init 1');            
            initVar(); 
            addButton(); 
        };
 

        //初始化变量
        function initVar() {
            console.log('Forhelper initVar 2');  
            GoodsPrice =  document.querySelector('.mod-goods-price') ;
            if(GoodsPrice){
                hasDone = true;
            }
        }
  

        // 添加增序sku按钮
        function addButton() {            
            console.log('Forhelper addButton 3');  
            let $batchbutton = $(`<button type="button" class="el-button el-button--primary el-button--small"><span> 增序填充SKU </span></button>`);
           
            $(GoodsPrice.querySelector('div.batch-setting-box')).append($batchbutton);            
            $batchbutton.click(batchClick);   
        }
       
        //生成增序skuCode
        function skuBuilder(skuCode,index){
            if(!skuCode) return '';
            let result = '';             
            index = '00' + index;              
            result =  skuCode + '-' + index.substr(index.length - 3);

            return result.toUpperCase();

        }
        //生成增序spuCode
        function spuBuilder(skuCode){
            if(!skuCode) return '';
            let result = '';                         
            result =  'C' + skuCode.substr(0,1) + 'EB-' + skuCode.substr(1);

            return result.toUpperCase();

        }
        
        // 增序批量填充skuCode
        function batchClick(event) {
            console.log(event)
            
            let querySelectorskuCode = 'div.batch-setting-item.batch-setting-item--skuCode > div > input'
            let skuCode = GoodsPrice.querySelector(querySelectorskuCode).value.trim();
            console.log(skuCode)
             
            //填充sku
            let querySelectorSkutable = ' div.sku-table > div > div.el-table__body-wrapper > table > tbody >  tr > td .el-input--skuCode input'
            GoodsPrice.querySelectorAll(querySelectorSkutable).forEach((item,index) => {
                item.value =skuBuilder(skuCode,index+1);
                item.dispatchEvent(new Event('input'));
            }) 

            //填充spu
            let querySelectorSpuCode = ' div.mod-sku-code > div > input'
            let el = document.querySelector(querySelectorSpuCode);
            el.value = spuBuilder(skuCode);
            el.dispatchEvent(new Event('input'));
        }
      
 
    }
 
    window.onload = function() {
         // 不支持则用定时器检测的办法
         Interval = setInterval(function() {
              hashChangeFire();  // TODO，对应新的hash执行的操作函数 
    }, 3000);                
    };

    
//监听触发操作
function hashChangeFire(){
    if(hasDone) { 
        clearInterval(Interval);      
        return;
    } 
    let plugin = new Forhelper();
    plugin.init();   
}
    

})();
